package com.za.plugin.transfer.func;



import com.za.plugin.pojo.Content;
import com.za.plugin.util.StrUtil;

import java.util.List;

// 把 format(a,b,c) 转为 round(a,b)
public class FormatFunctionTransfer implements FunctionTransfer {
    @Override
    public boolean isSupport(String sql) {
        return clearSpace(sql).contains(" format(");
    }


    private String clearSpace(String sql) {
        return sql.toLowerCase().replaceAll("([ ,]+)format\\s*\\(", "$1format(");

    }

    @Override
    public String transfer(String sql) {
        sql = clearSpace(sql);
        if (sql.contains(" format(")) {
            int idx = sql.indexOf(" format(");
            StringBuilder sb = new StringBuilder();
            int left = 0;
            while (idx >= 0) {
                Content expectContent = StrUtil.getExpectContent(sql, idx + 7);
                assert expectContent != null;
                int end = expectContent.getEnd();
                List<String> segment = StrUtil.getSegment(sql, idx + 8, end - 1);

                sb.append(sql, left, idx).append(" round(").append(segment.get(0)).append(",").append(segment.get(1)).append(")");
                idx = sql.indexOf(" format(", idx + 8);
                if (idx == -1) {
                    sb.append(sql.substring(end));
                }
                left = end;
            }
            sql = sb.toString();
        }
        return sql;
    }
}
